package com.companyName.sample.service.business;

import com.companyName.sample.bean.dto.sys.UserInfoDto;
import com.companyName.sample.common.exception.BusinessException;
import com.companyName.sample.common.util.CommUtil;
import com.companyName.sample.data.cache.JedisCache;
import com.companyName.sample.data.entity.UserInfoExample;
import com.companyName.sample.data.entity.UserInfoPo;
import com.companyName.sample.data.mapper.UserInfoMapper;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * Created by guo.jun on 2016/3/29.
 */
@Component
public class UserInfoBiz extends UserInfoPo {


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    public UserInfoDto getUserInfo(Integer userId) throws BusinessException {
        UserInfoPo ui = userInfoMapper.selectByPrimaryKey(userId);
        UserInfoDto userInfoDto = new UserInfoDto();
        CommUtil.copyProperties(ui,userInfoDto);
        return userInfoDto;
    }


    public List<UserInfoDto> getUserInfoList(UserInfoExample userInfo, int pageId, int pageSize) throws BusinessException {
        RowBounds rowBounds = new RowBounds(pageId * pageSize, pageSize);
        List retlist = new ArrayList<UserInfoDto>();
        List<UserInfoPo> userInfoList = userInfoMapper.selectByExampleAndRowBounds(userInfo, rowBounds);
        for(UserInfoPo ui:userInfoList){
            UserInfoDto UserInfoDto = new UserInfoDto();
            CommUtil.copyProperties(ui,UserInfoDto);
            retlist.add(UserInfoDto);
        }
        return retlist;
    }

    public int putUserInfo(UserInfoPo userInfo) throws BusinessException {
        Random r = new Random();
        userInfo.setPassword(UUID.randomUUID().toString());
        userInfo.setUsername("admin" + r.nextInt());
        int res = userInfoMapper.insert(userInfo);
        return res;
    }

    public int postUserInfo(UserInfoPo userInfo) throws BusinessException {
        int res = userInfoMapper.updateByPrimaryKey(userInfo);
        return res;
    }


    public int deleteUserInfo(UserInfoExample userInfo) throws BusinessException {
        int res = userInfoMapper.deleteByExample(userInfo);
        return res;
    }

    /*
     * 增加缓存对象
     */
    public void putUserInfoForCache(UserInfoPo userInfo){
        redisTemplate.opsForValue().set("userInfoMapper-" + userInfo.getUsername(), userInfo);
    }

}
